//index.js
//获取应用实例
const app = getApp()
const Util = require('../../utils/util.js');

Page({
    data: {},

    onLoad: function() {
        wx.getStorage({
            key: 'user',
            success: res => {
                console.log(res);
                if (!res.data) {
                    return;
                }
                let data = JSON.parse(res.data);
                app.login(data.userId, data.userName);
                wx.reLaunch({
                    url: '/pages/home/home'
                })
            }
        })
        this.password = '';
        this.phoneNumber = '';
        this.userName = '';
    },

    inputPhoneNumber: function(e) {
        this.phoneNumber = e.detail.value;
    },

    inputPassword: function(e) {
        this.password = e.detail.value;
    },

    inputUsername: function(e) {
        this.userName = e.detail.value;
    },

    onRegisterButton: async function(e) {
        let b = app.globalData.baseURL;
        let resp = await Util.asyncHttpPost(b + 'register', {
            userId: this.phoneNumber,
            userName: this.userName,
            pword: this.password
        });
        console.log(resp.data);
        if (resp.data.startsWith('1')) {
            app.login(this.phoneNumber, this.userName);
            wx.reLaunch({
                url: "/pages/home/home"
            });
        } else {
            wx.showModal({
                title: resp.data
            });
        }
    },

    onLoginButton: async function(e) {
        let b = app.globalData.baseURL;
        let resp = await Util.asyncHttpPost(b + 'userLogin', {
            userId: this.phoneNumber
        });
        console.log('response', resp);
        if (resp.data) {
            if (resp.data[0].pword !== this.password) {
                wx.showModal({
                    title: '登陆失败：密码不正确'
                });
            } else {
                app.login(this.phoneNumber, resp.data[0].userName);
                wx.reLaunch({
                    url: "/pages/home/home"
                });
            }
        } else {
            wx.showModal({
                title: '登陆失败。'
            })
        }
    }
})